//
//  YZMRegisterViewController.m
//  YZMicroStock
//
//  Created by Lv.Dongdong on 16/3/25.
//  Copyright © 2016年 cqjr. All rights reserved.
//

#import "YZMRegisterViewController.h"
#import "YZMHintInputView.h"
#import "YZNetworkManager.h"
#import "YZGeneralResultModel.h"
#import "YZClient+Account.h"
#import "Zhugeio/Zhuge.h"
#import "YZMLoginViewController.h"
#import "CheckCodeView.h"

@interface YZMRegisterViewController () <UITextFieldDelegate,CheckCodeViewDelegate>

@property (nonatomic, strong) YZMHintInputView *phoneNumberView;

@property (weak, nonatomic) IBOutlet UIView *viewPhoneNumber;

@property (weak, nonatomic) IBOutlet UILabel *labelPhoneInfo;

@property (weak, nonatomic) IBOutlet UITextField *textFieldPhone;

@property (weak, nonatomic) IBOutlet UIView *viewCode;

@property (weak, nonatomic) IBOutlet UILabel *labelCodeInfo;

@property (weak, nonatomic) IBOutlet UITextField *textFieldCode;

@property (weak, nonatomic) IBOutlet UIView *viewLine;

@property (weak, nonatomic) IBOutlet UIButton *btnCode;

@property (weak, nonatomic) IBOutlet UILabel *labelCode;

@property (weak, nonatomic) IBOutlet UIButton *btnNext;

@property (weak, nonatomic) IBOutlet UIButton *btnLogin;

@property (weak, nonatomic) IBOutlet UILabel *labelAccountInfo;

@property (nonatomic, copy) NSString *nextPageName;
@property (nonatomic, strong) NSDictionary *nextPageParams;
@property (nonatomic, copy) NSString *srcPageName;

@property (nonatomic, assign) BOOL dismissFlag;
@property (nonatomic, strong) void (^srcAction)();
@property (nonatomic, strong) void (^backAction)();

@property (nonatomic, strong) NSTimer *timer;

@property (nonatomic, assign) NSInteger seconds;

@property (nonatomic, strong) NSString *oldContext;

@property (nonatomic, strong) NSString *codeContext;

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *constraintBtnNextTop;

@property (weak, nonatomic) IBOutlet UILabel *labelBigPhone;

@property (weak, nonatomic) CheckCodeView *codeView;


@end

@implementation YZMRegisterViewController {
    UIButton *_nextStepButton;
    UILabel *_detailNumberLabel;
}

- (id)init {
    if (self = [super init]) {
        self.view.backgroundColor = [YZMAppStyle appBackgroundColor];
        self.title = @"注册";
        self.hidesBottomBarWhenPushed = YES;
    }
    return self;
}

+ (instancetype)createWithParams: (NSDictionary *)params
{
    YZMRegisterViewController *ctrl = [[self alloc] init];
    ctrl.nextPageName = params[YZNEXTPAGE];
    ctrl.nextPageParams = params[YZNEXTPAGEPARAMS];
    ctrl.srcPageName  = params[YZSOURCEPAGE];
    ctrl.dismissFlag = [params[YZDismissFlag] boolValue];
    ctrl.srcAction = params[YZSOURCEACTION];
    ctrl.backAction = params[YZBACKACTION];
    return ctrl;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self createObjects];
    
}

- (BOOL)shouldAutoBackToPreviousController{
    
    YZMLoginViewController *VC = [YZMHCMInstance instanceWithControllerName:@"login"];
    if (VC) {
        
        [YZMHCMInstance popViewController];
    }
    
    return YES;
}

- (void)createObjects  {
    self.viewPhoneNumber.backgroundColor = [YZMAppStyle colorForMain];
    self.viewCode.backgroundColor = [YZMAppStyle colorForMain];
    self.labelPhoneInfo.textColor = [YZMAppStyle colorForWhite];
    self.labelCodeInfo.textColor = [YZMAppStyle colorForWhite];
    self.textFieldPhone.textColor = [YZMAppStyle colorForWhite];
    self.textFieldCode.textColor = [YZMAppStyle colorForWhite];
    self.labelCode.textColor = [YZMAppStyle colorForIconColor];
    self.viewLine.backgroundColor = [YZMAppStyle colorForIconColor];
    self.labelAccountInfo.textColor = [YZMAppStyle colorForWhite];
    [self.textFieldPhone setValue:[YZMAppStyle colorForWhite] forKeyPath:@"_placeholderLabel.textColor"];
     [self.textFieldCode setValue:[YZMAppStyle colorForWhite] forKeyPath:@"_placeholderLabel.textColor"];
    UIView *leftViewOne = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 30, 44)];
    self.textFieldPhone.leftView = leftViewOne;
    self.textFieldPhone.leftViewMode = UITextFieldViewModeAlways;
    UIView *leftViewTwo = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 30, 44)];
    self.textFieldCode.leftView = leftViewTwo;
    self.textFieldCode.leftViewMode = UITextFieldViewModeAlways;
    [self.textFieldPhone addTarget:self action:@selector(textFieldchange:) forControlEvents:UIControlEventEditingChanged];
    [self.textFieldCode addTarget:self action:@selector(textFieldCodeChange:) forControlEvents:UIControlEventEditingChanged];
    self.textFieldPhone.delegate = self;
    UIButton *btnCleanOne = [self.textFieldPhone valueForKey:@"_clearButton"];
    [btnCleanOne setImage:[UIImage imageNamed:@"cleanimage.png"] forState:UIControlStateNormal];
    [btnCleanOne setImage:[UIImage imageNamed:@"cleanimage.png"] forState:UIControlStateHighlighted];
    UIButton *btnCleanTwo = [self.textFieldCode valueForKey:@"_clearButton"];
    [btnCleanTwo setImage:[UIImage imageNamed:@"cleanimage.png"] forState:UIControlStateNormal];
    [btnCleanTwo setImage:[UIImage imageNamed:@"cleanimage.png"] forState:UIControlStateHighlighted];
    self.labelBigPhone.font = [YZMAppStyle largeSizeFont];
    self.labelBigPhone.textColor = [YZMAppStyle buttonSelectedColor];
    self.btnNext.clipsToBounds = YES;
    self.btnNext.layer.cornerRadius = 3.0;
    self.btnNext.layer.masksToBounds = YES;
    self.btnNext.layer.borderWidth=1.0;
    self.btnNext.layer.borderColor=[YZMAppStyle colorForbuttonLineColor].CGColor;
    [self.btnNext setBackgroundColor:[YZMAppStyle appBackgroundColor]];
     [self.btnNext setTitleColor:[YZMAppStyle colorForGrayText] forState:UIControlStateNormal];
    [self.btnNext.titleLabel setFont:[YZMAppStyle largeSizeFont]];
    self.btnNext.userInteractionEnabled = NO;
    [self.btnNext addTarget:self action:@selector(nextStepCheck:) forControlEvents:UIControlEventTouchUpInside];
    [self.btnLogin setTitleColor:[YZMAppStyle colorForBlueText] forState:UIControlStateNormal];
    [self.btnLogin.titleLabel setFont:[YZMAppStyle mediumSizeFont]];
    [self.btnLogin  addTarget:self action:@selector(pushLogin) forControlEvents:UIControlEventTouchUpInside];
    [self.btnCode addTarget:self action:@selector(requestGainCode) forControlEvents:UIControlEventTouchUpInside];
}

- (void)requestGainCode{
    if (![_oldContext yz_isValidPhoneString]) {
        [MBProgressHUD showMessage:@"请输入正确的手机号码"];
        return;
    } else {
        BOOL ynFlat = [self phoneCheck];
        if (!ynFlat) {
            [MBProgressHUD showMessage:@"请输入正确的手机号码"];
            return;
        }
    }
    self.codeView = [[NSBundle mainBundle] loadNibNamed:NSStringFromClass([CheckCodeView class]) owner:self options:nil][0];
    self.codeView.delegate = self;
    [self.codeView show];
    
}

- (void)checkCode:(NSString *)strCode{
    [self fecthMobileAuthCode:strCode];
}

- (void)fecthMobileAuthCode:(NSString *)checkCode {
    
    WS(ws)
    
    [YZClient getMobileAuthCode:self.oldContext withCheckCode:checkCode success:^(NSURLSessionDataTask *task, id responseObject) {
        
        [ws returnWithResult:responseObject];
    } failure:^(NSError *error) {
        
        [error yz_showMessage];
    }];
}

- (void)gainCodeWithPhoneString:(NSString *)phoneString{
    WS(ws);
    [YZClient getMobileAuthCode:phoneString success:^(NSURLSessionDataTask *task, id responseObject) {
        [ws returnWithResult:responseObject];
    } failure:^(NSError *error) {
        [error yz_showMessage];
    }];
}

- (void)returnWithResult:(YZGeneralResultModel *)responseObject {
    
    if (responseObject.code == 501) {
        [responseObject showMessage];
        return;
    } else if (responseObject.code == 100) {
        [self configTimer];
        [self.codeView removeFromSuperview];
        [MBProgressHUD showMessage:[NSString stringWithFormat:@"验证码已发送至%@,请注意查收！",self.oldContext]];
    }else if (responseObject.code == 101){
        [self configTimer];
        [self.codeView removeFromSuperview];
         [MBProgressHUD showMessage:[NSString stringWithFormat:@"验证码已发送至%@,请注意查收！",self.oldContext]];
    }else{
         [responseObject showMessage];
    }
}


- (void)configTimer{
    self.seconds = 59;
    self.labelCode.text = [NSString stringWithFormat:@"%lds后重发",(long)self.seconds];
    self.timer = [NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(getCode) userInfo:nil repeats:YES];
}

- (void)getCode{
    self.seconds--;
    if (self.seconds < 1) {
        self.btnCode.userInteractionEnabled = YES;
        [self.timer invalidate];
        self.timer  = nil;
        self.labelCode.text = @"获取验证码";
    }else{
        self.labelCode.text = [NSString stringWithFormat:@"%lds后重发",(long)self.seconds];
        self.btnCode.userInteractionEnabled = NO;
    }
}

- (void)pushLogin {
    [self.textFieldPhone resignFirstResponder];
    
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    
    if (self.nextPageName) {
        params[YZNEXTPAGE] = self.nextPageName;
    }
    
    if (self.srcPageName) {
        params[YZSOURCEPAGE] = self.srcPageName;
    }
    
    if (self.nextPageParams) {
        params[YZNEXTPAGEPARAMS] = self.nextPageParams;
    }
    
    if (self.srcAction) {
        params[YZSOURCEACTION]=self.srcAction;
    }
    
    if (self.backAction) {
        params[YZBACKACTION]=self.backAction;
    }
    
    params[YZDismissFlag] = @(self.dismissFlag);
    
    [YZMHCMInstance pushAfterRootWithName:@"login" andParams:params atIndex:self.tabBarController.selectedIndex];
}

- (void)nextStepCheck:(UIButton *)send {
    [self.phoneNumberView.textField resignFirstResponder];
    WS(ws);
    [YZClient registerGoNextStepWithMobile:self.oldContext withCheckCode:self.codeContext Success:^(NSURLSessionDataTask *task, id responseObject) {
        
        YZGeneralResultModel *topModel = responseObject;
        NSMutableDictionary *params = [NSMutableDictionary dictionary];
        if ([topModel.data isEqualToString:ws.oldContext]) {
            
            params[@"mobile"] = ws.oldContext;
            params[@"code"] = ws.codeContext;
            
            if (self.nextPageName) {
                params[YZNEXTPAGE] = self.nextPageName;
            }
            
            if (self.srcPageName) {
                params[YZSOURCEPAGE] = self.srcPageName;
            }
            
            if (self.nextPageParams) {
                params[YZNEXTPAGEPARAMS] = self.nextPageParams;
            }
            
            if (self.srcAction) {
                params[YZSOURCEACTION]=self.srcAction;
            }
            
            if (self.backAction) {
                params[YZBACKACTION]=self.backAction;
            }
            
            params[YZDismissFlag] = @(self.dismissFlag);
            
#if defined(DEBUG_MODE)
            
#elif defined(YZOuterDiscxg)
            [[Zhuge sharedInstance] track:@"注册-开始注册" properties:nil];
#endif
            [YZMCMInstance pushViewControllerWithName:@"regAuth" andParams:params];
        } else {
            
            [topModel showMessage];
        }
    } failure:^(NSError *error) {
        
        [error yz_showMessage];
    }];

}


- (void)textFieldchange:(UITextField *)send {
    
    _oldContext = send.text;
    if ([send.text length] > 11) {
        _oldContext = [send.text substringToIndex:11];
        send.text = _oldContext;
    }
    if (_oldContext.length > 0) {
        self.labelBigPhone.text = _oldContext;
        self.constraintBtnNextTop.constant = 50;
    }else{
        self.labelBigPhone.text = @"";
        self.constraintBtnNextTop.constant = 15;
    }
    if (_oldContext.length == 11) {
        if (![send.text yz_isValidPhoneString]) {
            [MBProgressHUD showMessage:@"请输入正确的手机号码"];
            return;
        } else {
            BOOL ynFlat = [self phoneCheck];
            if (!ynFlat) {
                [MBProgressHUD showMessage:@"请输入正确的手机号码"];
                return;
            }
            
        }
    }
}

- (BOOL)checkIsPhone{
    if (_oldContext.length == 11) {
        if ([_oldContext yz_isValidPhoneString]) {
            BOOL ynFlat = [self phoneCheck];
            return ynFlat;
        }
        return NO;
    }
    return NO;
}

- (void)textFieldCodeChange:(UITextField *)send{
    _codeContext = send.text;
    if (_codeContext.length > 0 && _oldContext.length == 11 && [self checkIsPhone]) {
        self.btnNext.userInteractionEnabled = YES;
        [self.btnNext setTitleColor:[YZMAppStyle colorForBlackText] forState:UIControlStateNormal];
        self.btnNext.backgroundColor = [YZMAppStyle buttonSelectedColor];
        [self.btnNext.layer setBorderWidth:0];
    }else{
        self.btnNext.userInteractionEnabled = NO;
        [self.btnNext setTitleColor:[YZMAppStyle colorForGrayText] forState:UIControlStateDisabled];
        [self.btnNext.layer setBorderWidth:1.0f];
         self.btnNext.backgroundColor = [YZMAppStyle appBackgroundColor];
    }
    
}

//- (void)showAuthCodeCheckAlertView {
//    
//    if (kNetworkNotReachability) {
//        
//        [MBProgressHUD showMessage:@"网络无法连接，请联网后重试"];
//        
//        return;
//    }
//    
//    self.alertView = [YZDAlertView new];
//    self.alertView.titleLabel.text = @"获取验证码前，请您先填写下面数字";
//    self.alertView.titleLabel.font = [YZDAppStyle mediumSizeFont];
//    
//    UIView *customView = [[UIView alloc] init];
//    self.alertView.customView = customView;
//    
//    UIView *contentView = [[UIView alloc] init];
//    //    contentView.layer.cornerRadius = 5.0;
//    contentView.layer.masksToBounds = YES;
//    //    contentView.layer.borderColor = [YZDAppStyle colorForGrayUnable].CGColor;
//    //    contentView.layer.borderWidth = 1;
//    [customView addSubview:contentView];
//    [contentView mas_makeConstraints:^(MASConstraintMaker *make) {
//        
//        make.top.bottom.equalTo(customView);
//        make.width.mas_equalTo(220);
//        make.centerX.equalTo(customView.mas_centerX);
//        make.height.mas_equalTo(32);
//    }];
//    
//    self.picAuthCodeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
//    self.picAuthCodeBtn.adjustsImageWhenHighlighted = NO;
//    self.picAuthCodeBtn.backgroundColor = [YZDAppStyle colorForGrayUnable];
//    [self.picAuthCodeBtn addTarget:self action:@selector(refreshPicAuthCode) forControlEvents:UIControlEventTouchUpInside];
//    [contentView addSubview:self.picAuthCodeBtn];
//    [self.picAuthCodeBtn mas_makeConstraints:^(MASConstraintMaker *make){
//        
//        make.top.bottom.left.equalTo(contentView);
//        make.right.equalTo(contentView.mas_centerX);
//    }];
//    
//    //下载图片验证码
//    [self joiningWithUrl];
//    
//    self.picAuthCodeTF = [[UITextField alloc] init];
//    self.picAuthCodeTF.keyboardType = UIKeyboardTypeNumberPad;
//    self.picAuthCodeTF.clearButtonMode = UITextFieldViewModeAlways;
//    self.picAuthCodeTF.borderStyle = UITextBorderStyleLine;
//    self.picAuthCodeTF.layer.borderColor = [YZDAppStyle colorForGrayUnable].CGColor;
//    self.picAuthCodeTF.layer.borderWidth = 1.0;
//    self.picAuthCodeTF.textColor = [YZDAppStyle colorForSecondaryText];
//    self.picAuthCodeTF.font = [YZDAppStyle mediumSizeFont];
//    self.picAuthCodeTF.placeholder = @"请输入";
//    [contentView addSubview:self.picAuthCodeTF];
//    [self.picAuthCodeTF mas_makeConstraints:^(MASConstraintMaker *make){
//        
//        make.top.bottom.height.equalTo(self.picAuthCodeBtn);
//        make.left.equalTo(self.picAuthCodeBtn.mas_right).offset(8);
//        make.right.equalTo(contentView.mas_right);
//        
//    }];
//    
//    UIView *blankView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 10, 0)];
//    self.picAuthCodeTF.leftView = blankView;
//    self.picAuthCodeTF.leftViewMode = UITextFieldViewModeAlways;
//    self.picAuthCodeTF.delegate = self.alertView;
//    
//    WS(ws)
//    self.alertView.confirmHandle = ^(){
//        
//        [ws.picAuthCodeTF resignFirstResponder];
//        
//        NSString *authText =  ws.picAuthCodeTF.text;
//        if (!authText || authText.length == 0) {
//            
//            [MBProgressHUD showMessage:@"请先输入图片中的验证码"];
//            return NO;
//        }
//        
//        if (![authText yz_isValidAuthCode]) {
//            
//            [MBProgressHUD showMessage:@"请输入4位数字验证码"];
//            return NO;
//        }
//        
//        if (self.scene == SEND_CODE_SCENE_FOR_BIND_NEWMOBILE) {
//            if ([ws.phoneNumberView.textField.text isEqualToString:YZDUSInstance.user.detail.loginMobileNoHidden]) {
//                [MBProgressHUD showMessage:@"新手机号码不能和旧手机号相同"];
//                [ws isAlertViewHidden:YES];
//                return NO;
//            }
//        }
//        
////        if (self.scene == SEND_CODE_SCENE_FOR_REGISTER) {
////            
////            [ws fecthMobileAuthCode:authText];
////        } else if (self.scene == SEND_CODE_SCENE_FOR_FORGET_PWD) {
////            
////            [ws forget_getMobileAuthCode:authText];
////        }else if (self.scene == SEND_CODE_SCENE_FOR_UNBIND_MOBILE){
////            
////            [ws unbind_getMobileImessageWithcheckCode:authText];
////            
////        }else if (self.scene == SEND_CODE_SCENE_FOR_BIND_NEWMOBILE){
////            
////            [ws bind_getMobileImessageWithCheckCode:authText];
////        }
//        
//        return NO;
//    };
//    
//    [self.alertView show];
//}


- (BOOL)phoneCheck {
    NSInteger phoneNum = [[self.textFieldPhone.text substringToIndex:2] integerValue];
    switch (phoneNum) {
        case 13:
        case 14:
        case 15:
        case 17:
        case 18:
        case 19:
            return YES;
            break;
        default:
            return NO;
            break;
    }
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [self.view endEditing:YES];
}


@end
